from flask import render_template, redirect, flash, url_for
from flask_login import login_required, login_user
from . import admin_bp
from .forms import AdminLoginForm
from ..models import Admin
from ..main.views import counter


@admin_bp.route('/login', methods=['GET', 'POST'])
def login():
    form = AdminLoginForm()
    if form.validate_on_submit():
        admin = Admin.query.filter_by(name=form.name.data).first()
        if admin and admin.verify_password(form.password.data):
            login_user(admin)
            return redirect(url_for('admin.admin'))
        else:
            flash('Invalid Username or Password!', 'danger')
    return render_template('admin_login.html', form=form)

@admin_bp.route('/')
@login_required
def admin():
    return render_template('admin.html', count=counter.value)
